// pages/post-detail/post-detail.js
Page({
  /**
   * 页面的初始数据
   */
  data: {
    postId: null,
    postData: {},
    commentList: [],
    showCommentInput: false,
    commentText: '',
    replyPlaceholder: '',
    currentCommentId: null,
    currentReplyId: null,
    currentReplyName: '',
    isOwnPost: false,
    // 添加图标路径对象，方便管理
    icons: {
      back: '/images/back.png',
      more: '/icon/更多.svg',
      defaultAvatar: '/images/default-avatar.png',
      location: '/images/location.png',
      view: '/icon/围观.svg',
      comment: '/icon/评论.svg',
      like: '/icon/点赞.svg',
      likeFilled: '/icon/已点赞.svg', // 默认使用围观图标代替
      collect: '/icon/收藏.svg',
      collectFilled: '/icon/已收藏.svg',
      share: '/icon/分享.svg',
      reply: '/icon/评论.svg'
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log('帖子详情页onLoad, options:', options);
    
    // 检查图标路径，设置替代图标
    this.checkIconPaths();
    
    if (options && options.id) {
      this.setData({
        postId: options.id
      });
      
      // 加载帖子详情
      this.getPostDetail(options.id);
      
      // 加载评论列表
      this.getCommentList(options.id);
    } else {
      wx.showToast({
        title: '参数错误',
        icon: 'none'
      });
      setTimeout(() => {
        wx.navigateBack();
      }, 1500);
    }
  },

  /**
   * 检查图标路径，设置替代图标
   */
  checkIconPaths: function() {
    // 如果没有点赞图标，使用围观图标代替
    let icons = this.data.icons;
    
    // 如果没有已点赞图标，使用已围观图标代替
    if (!icons.likeFilled) {
      icons.likeFilled = '/icon/已围观.svg';
    }
    
    // 更新图标路径
    this.setData({ icons });
  },

  /**
   * 获取帖子详情
   */
  getPostDetail: function (postId) {
    console.log('获取帖子详情, ID:', postId);
    // 模拟请求后端API
    const postData = this.getMockPostDetail(postId);
    this.setData({
      postData: postData,
      isOwnPost: postData.isOwnPost || false
    });
  },

  /**
   * 获取评论列表
   */
  getCommentList: function (postId) {
    console.log('获取评论列表, ID:', postId);
    // 模拟请求后端API
    const commentList = this.getMockCommentList(postId);
    this.setData({
      commentList: commentList
    });
  },

  /**
   * 模拟帖子详情数据
   */
  getMockPostDetail: function (postId) {
    // 返回模拟数据
    // 实际开发中应该从服务器获取
    console.log('使用模拟数据, ID:', postId);
    
    // 将postId转为数字
    const id = parseInt(postId, 10);
    
    // 默认数据
    const defaultData = {
      id: id,
      author: '用户名',
      avatar: '/assets/icons/default-avatar.png',
      publishTime: '刚刚',
      isFollowed: false,
      content: '这是帖子内容',
      watchCount: 0,
      collectCount: 0,
      commentCount: 0,
      shareCount: 0,
      likeCount: 0,
      isLiked: false,
      isCollected: false,
      isWatched: false,
      isOwnPost: false
    };
    
    // 根据ID返回不同的数据
    const dataMap = {
      1: {
        author: '张三',
        avatar: 'https://objectstorageapi.bja.sealos.run/a0qepsyj-001/text/Default%20avatar/d907281-0.png',
        publishTime: '10分钟前',
        content: '这是我的第一条动态内容，最近开始学习前端开发，感觉挺有意思的。HTML和CSS还比较简单，JavaScript就需要更多的时间去理解了。分享一些学习资源，希望对大家有帮助！',
        images: [
          'https://objectstorageapi.bja.sealos.run/a0qepsyj-001/miniprogram-cdn/post-image1.png',
          'https://objectstorageapi.bja.sealos.run/a0qepsyj-001/miniprogram-cdn/post-image2.png'
        ],
        location: '北京市海淀区',
        watchCount: 32,
        collectCount: 15,
        commentCount: 8,
        shareCount: 5,
        likeCount: 20,
        relatedContent: {
          type: '岗位',
          title: '前端开发工程师',
          desc: '负责公司产品的前端开发，要求熟悉HTML、CSS、JavaScript等技术',
          coverUrl: 'https://objectstorageapi.bja.sealos.run/a0qepsyj-001/miniprogram-cdn/job-cover.png'
        },
        group: {
          name: '前端开发交流群',
          avatar: 'https://objectstorageapi.bja.sealos.run/a0qepsyj-001/miniprogram-cdn/group-avatar.png'
        },
        tags: ['前端开发', 'JavaScript', 'Vue.js']
      },
      2: {
        author: '李四',
        avatar: 'https://objectstorageapi.bja.sealos.run/a0qepsyj-001/text/Default%20avatar/d907281-1.png',
        publishTime: '1小时前',
        content: '分享今日学习心得，学习了React框架的基础知识，感觉组件化思想很强大，可以大大提高开发效率。',
        images: [
          'https://objectstorageapi.bja.sealos.run/a0qepsyj-001/miniprogram-cdn/post-image3.png'
        ],
        watchCount: 45,
        collectCount: 0,
        commentCount: 3,
        shareCount: 0,
        likeCount: 12,
        relatedContent: {
          type: '活动',
          title: '校园招聘会',
          desc: '本周五在学校体育馆举行大型校园招聘会，有多家知名企业参与',
          coverUrl: 'https://objectstorageapi.bja.sealos.run/a0qepsyj-001/miniprogram-cdn/event-cover.png'
        },
        group: {
          name: '校园招聘交流群',
          avatar: 'https://objectstorageapi.bja.sealos.run/a0qepsyj-001/miniprogram-cdn/group-avatar2.png'
        },
        tags: ['校园招聘', '求职经验']
      },
      3: {
        author: '王五',
        avatar: 'https://objectstorageapi.bja.sealos.run/a0qepsyj-001/text/Default%20avatar/d928162-0.png',
        publishTime: '今天 10:30',
        content: 'JAVA比赛是由腾讯的音乐大赛主办，奖金丰厚，欢迎有兴趣的同学报名参加！比赛将在下个月初举行，现在开始接受报名。',
        watchCount: 28,
        collectCount: 6,
        commentCount: 0,
        shareCount: 2,
        likeCount: 8,
        relatedContent: {
          type: '比赛',
          title: 'JAVA编程大赛',
          desc: '由腾讯音乐主办的全国高校JAVA编程挑战赛，奖金丰厚',
          coverUrl: 'https://objectstorageapi.bja.sealos.run/a0qepsyj-001/miniprogram-cdn/competition-cover.png'
        }
      },
      4: {
        author: '赵六',
        avatar: 'https://objectstorageapi.bja.sealos.run/a0qepsyj-001/text/Default%20avatar/d928162-1.png',
        publishTime: '昨天 15:42',
        content: '今日参加了编程实践活动，收获颇丰！和团队一起完成了一个小型项目，学到了很多团队协作的经验。',
        images: [
          'https://objectstorageapi.bja.sealos.run/a0qepsyj-001/miniprogram-cdn/post-image1.png',
          'https://objectstorageapi.bja.sealos.run/a0qepsyj-001/miniprogram-cdn/post-image2.png',
          'https://objectstorageapi.bja.sealos.run/a0qepsyj-001/miniprogram-cdn/post-image3.png'
        ],
        watchCount: 36,
        collectCount: 20,
        commentCount: 12,
        shareCount: 8,
        likeCount: 30
      }
    };
    
    // 合并默认数据和特定数据
    return { ...defaultData, ...(dataMap[id] || {}) };
  },

  /**
   * 模拟评论列表数据
   */
  getMockCommentList: function (postId) {
    // 返回模拟数据
    // 实际开发中应该从服务器获取
    
    // 将postId转为数字
    const id = parseInt(postId, 10);
    
    // 默认返回空数组
    if (!id) return [];
    
    // 根据ID返回不同的评论列表
    switch (id) {
      case 1:
        return [
          {
            id: 1,
            username: '小明',
            userid: 'user001',
            avatar: 'https://objectstorageapi.bja.sealos.run/a0qepsyj-001/text/Default%20avatar/d907281-1.png',
            content: '感谢分享，这些资源对我很有帮助！',
            time: '8分钟前',
            likeCount: 5,
            isLiked: false
          },
          {
            id: 2,
            username: '小红',
            userid: 'user002',
            avatar: 'https://objectstorageapi.bja.sealos.run/a0qepsyj-001/text/Default%20avatar/d928162-0.png',
            content: '学习前端确实是个不错的选择，现在市场需求很大。',
            time: '7分钟前',
            likeCount: 2,
            isLiked: false
          }
        ];
      case 2:
        return [
          {
            id: 3,
            username: '小华',
            userid: 'user003',
            avatar: 'https://objectstorageapi.bja.sealos.run/a0qepsyj-001/text/Default%20avatar/d928162-1.png',
            content: '加油！继续坚持学习！',
            time: '59分钟前',
            likeCount: 1,
            isLiked: false
          }
        ];
      case 4:
        return [
          {
            id: 4,
            username: '小李',
            userid: 'user004',
            avatar: 'https://objectstorageapi.bja.sealos.run/a0qepsyj-001/text/Default%20avatar/d907281-0.png',
            content: '编程活动在哪报名？请问有链接吗？',
            time: '昨天',
            likeCount: 0,
            isLiked: false
          },
          {
            id: 5,
            username: '小王',
            userid: 'user005',
            avatar: 'https://objectstorageapi.bja.sealos.run/a0qepsyj-001/text/Default%20avatar/d907281-1.png',
            content: '我也想参加，求详细信息',
            time: '昨天',
            likeCount: 0,
            isLiked: false
          }
        ];
      default:
        return [];
    }
  },

  /**
   * 返回上一页
   */
  goBack: function () {
    wx.navigateBack();
  },

  /**
   * 显示更多操作菜单
   */
  showMoreActions: function () {
    wx.showActionSheet({
      itemList: ['举报', '收藏', '不感兴趣'],
      success: (res) => {
        switch (res.tapIndex) {
          case 0: // 举报
            wx.showToast({
              title: '举报成功',
              icon: 'success'
            });
            break;
          case 1: // 收藏
            this.toggleCollect();
            break;
          case 2: // 不感兴趣
            wx.showToast({
              title: '已减少此类内容推荐',
              icon: 'none'
            });
            break;
        }
      }
    });
  },

  /**
   * 查看用户资料
   */
  viewUserProfile: function (e) {
    const userid = e.currentTarget.dataset.userid || this.data.postData.userid;
    console.log('查看用户资料:', userid);
    
    // 实际开发中应该跳转到用户资料页
    wx.showToast({
      title: '查看用户资料功能开发中',
      icon: 'none'
    });
  },

  /**
   * 关注/取消关注
   */
  toggleFollow: function () {
    const isFollowed = !this.data.postData.isFollowed;
    
    this.setData({
      'postData.isFollowed': isFollowed
    });
    
    wx.showToast({
      title: isFollowed ? '已关注' : '已取消关注',
      icon: 'success'
    });
  },

  /**
   * 预览图片
   */
  previewImage: function (e) {
    const src = e.currentTarget.dataset.src;
    const images = this.data.postData.images || [];
    
    wx.previewImage({
      current: src,
      urls: images
    });
  },

  /**
   * 查看位置
   */
  viewLocation: function () {
    const location = this.data.postData.location;
    
    wx.showToast({
      title: '位置: ' + location,
      icon: 'none'
    });
  },

  /**
   * 查看群聊
   */
  viewGroup: function () {
    const group = this.data.postData.group;
    
    if (!group) return;
    
    wx.showToast({
      title: '进入群聊: ' + group.name,
      icon: 'none'
    });
  },

  /**
   * 搜索标签
   */
  searchTag: function (e) {
    const tag = e.currentTarget.dataset.tag;
    
    wx.showToast({
      title: '搜索: ' + tag,
      icon: 'none'
    });
  },

  /**
   * 点赞/取消点赞
   */
  toggleLike: function () {
    const isLiked = !this.data.postData.isLiked;
    const likeCount = isLiked 
      ? this.data.postData.likeCount + 1 
      : Math.max(0, this.data.postData.likeCount - 1);
    
    this.setData({
      'postData.isLiked': isLiked,
      'postData.likeCount': likeCount
    });
    
    wx.showToast({
      title: isLiked ? '已点赞' : '已取消点赞',
      icon: 'success'
    });
    
    // 模拟向服务器提交点赞状态
    console.log('向服务器提交点赞状态:', isLiked);
  },

  /**
   * 围观/取消围观
   */
  toggleWatch: function () {
    const isWatched = !this.data.postData.isWatched;
    const watchCount = isWatched 
      ? this.data.postData.watchCount + 1 
      : Math.max(0, this.data.postData.watchCount - 1);
    
    this.setData({
      'postData.isWatched': isWatched,
      'postData.watchCount': watchCount
    });
    
    wx.showToast({
      title: isWatched ? '已围观' : '已取消围观',
      icon: 'success'
    });
    
    // 模拟向服务器提交围观状态
    console.log('向服务器提交围观状态:', isWatched);
  },

  /**
   * 收藏/取消收藏
   */
  toggleCollect: function () {
    const isCollected = !this.data.postData.isCollected;
    const collectCount = isCollected 
      ? this.data.postData.collectCount + 1 
      : Math.max(0, this.data.postData.collectCount - 1);
    
    this.setData({
      'postData.isCollected': isCollected,
      'postData.collectCount': collectCount
    });
    
    wx.showToast({
      title: isCollected ? '已收藏' : '已取消收藏',
      icon: 'success'
    });
    
    // 模拟向服务器提交收藏状态
    console.log('向服务器提交收藏状态:', isCollected);
  },

  /**
   * 分享帖子
   */
  sharePost: function () {
    const shareCount = this.data.postData.shareCount + 1;
    
    this.setData({
      'postData.shareCount': shareCount
    });
    
    wx.showShareMenu({
      withShareTicket: true,
      menus: ['shareAppMessage', 'shareTimeline']
    });
  },

  /**
   * 点赞评论
   */
  likeComment: function (e) {
    const index = e.currentTarget.dataset.index;
    const isLiked = !this.data.commentList[index].isLiked;
    const likeCount = isLiked 
      ? this.data.commentList[index].likeCount + 1 
      : Math.max(0, this.data.commentList[index].likeCount - 1);
    
    this.setData({
      [`commentList[${index}].isLiked`]: isLiked,
      [`commentList[${index}].likeCount`]: likeCount
    });
  },

  /**
   * 回复评论
   */
  replyComment: function (e) {
    const index = e.currentTarget.dataset.index;
    const comment = this.data.commentList[index];
    
    this.setData({
      showCommentInput: true,
      replyPlaceholder: `回复 @${comment.username}：`,
      currentCommentId: comment.id,
      currentReplyName: comment.username,
      commentText: ''
    });
  },

  /**
   * 聚焦评论输入框
   */
  focusCommentInput: function () {
    this.setData({
      showCommentInput: true,
      replyPlaceholder: '说点什么...',
      currentCommentId: null,
      currentReplyName: '',
      commentText: ''
    });
  },

  /**
   * 隐藏评论输入框
   */
  hideCommentInput: function () {
    this.setData({
      showCommentInput: false
    });
  },

  /**
   * 评论输入变化
   */
  onCommentInput: function (e) {
    this.setData({
      commentText: e.detail.value
    });
  },

  /**
   * 提交评论
   */
  submitComment: function () {
    const content = this.data.commentText.trim();
    
    if (!content) {
      wx.showToast({
        title: '评论内容不能为空',
        icon: 'none'
      });
      return;
    }
    
    // 创建新评论
    const newComment = {
      id: new Date().getTime(),
      username: '当前用户',
      userid: 'current_user',
      avatar: 'https://objectstorageapi.bja.sealos.run/a0qepsyj-001/text/Default%20avatar/d928162-1.png',
      content: content,
      time: '刚刚',
      likeCount: 0,
      isLiked: false
    };
    
    // 更新评论列表和评论数量
    const commentList = [newComment, ...this.data.commentList];
    const commentCount = this.data.postData.commentCount + 1;
    
    this.setData({
      commentList: commentList,
      'postData.commentCount': commentCount,
      showCommentInput: false,
      commentText: ''
    });
    
    wx.showToast({
      title: '评论成功',
      icon: 'success'
    });
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    const postData = this.data.postData;
    
    return {
      title: postData.content.substring(0, 20) + '...',
      path: `/pages/post-detail/post-detail?id=${postData.id}`,
      imageUrl: postData.images && postData.images.length > 0 ? postData.images[0] : ''
    };
  },
  
  /**
   * 用户点击右上角分享到朋友圈
   */
  onShareTimeline: function () {
    const postData = this.data.postData;
    
    return {
      title: postData.content.substring(0, 40) + '...',
      query: `id=${postData.id}`,
      imageUrl: postData.images && postData.images.length > 0 ? postData.images[0] : ''
    };
  }
}) 